<?
/* check if user is logged in */
require "./includes/login_check.php";
require "./includes/db_connection.php";

function unit_token() {
	global $db;

	$generate = true;
	while($generate) {
		/* generate token */
		$token = substr(md5(uniqid(mt_rand()) . $_SERVER['REMOTE_ADDR']), 0, 32);

		/* check, that token is unique */
		try {
			$ps = $db->prepare('SELECT * FROM greenhouse WHERE token=?');
			$ps->execute(array($token));
			if(empty($ps->fetch())) {
				$generate = false;
			}
		} catch (Exception $e) {
			die("Chyba SQL [<b>$e</b>]<br>$token<br>$table");
		}

	}

	return $token;

}


echo("connected<br>");
$token = unit_token();
echo("token: <br><hr>".$token."<hr>");
try {
	$ps = $db->prepare("INSERT INTO greenhouse (user_id, name, token) VALUES (?,'',?)");
	$ps->execute(array($_SESSION['user_id'], $token));
} catch (Exception $e) {
	echo("Chyba");
}

/* go back to user page */
header("Location: ./user.php");
exit();
?>
